#!/bin/bash

#Add event log
add_sel(){
  MESSAGE="$*"

  busctl call \
    xyz.openbmc_project.Logging /xyz/openbmc_project/logging \
    xyz.openbmc_project.Logging.Create Create "ssa{ss}" "$MESSAGE" \
    xyz.openbmc_project.Logging.Entry.Level.Error 0
}

#Function : Power off a specific slot
power_off_slot(){
    local slot_number=$1
    local object_path="/xyz/openbmc_project/state/host${slot_number}"
    local service_name="xyz.openbmc_project.State.Host${slot_number}"
    local interface="xyz.openbmc_project.State.Host"
    local property="RequestedHostTransition"
    local value="xyz.openbmc_project.State.Host.Transition.Off"
    local ret=0

    echo "Powering off slot $slot_number..."

    busctl set-property "$service_name" "$object_path" "$interface" "$property" s "$value"

    ret=$?

    if [ $ret -eq 0 ]; then
        echo "Slot $slot_number powered off successfully."
    else
        echo "Failed to power off slot $slot_number." >&2
        return 1
    fi
}

#Function : Power off all slots(1 to 8)
power_off_all_slots(){
#Log the event before shutting down
    msg="Hosts 1 to 8 are being shut down due to the failure of more than 2 fan rotors."
    echo "${msg}"
    add_sel "${msg}"

#Power off each slot in sequence
    for slot in {1..8};
    do
      power_off_slot "$slot"
    done
}

#Main script execution
echo "Starting the shutdown process for all slots..."
power_off_all_slots
echo "Shutdown process completed."